package org.jeecg.modules.staff.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;


import org.jeecg.modules.param.area.entity.BikeSysArea;
import org.jeecg.modules.param.area.entity.BikeSysUserArea;
import org.jeecg.modules.param.area.mapper.BikeSysAreaMapper;
import org.jeecg.modules.param.area.mapper.BikeSysUserAreaMapper;

import org.jeecg.modules.param.staffUser.entity.LoginReq;
import org.jeecg.modules.param.staffUser.entity.LoginRes;
import org.jeecg.modules.param.staffUser.mapper.StaffMapper;
import org.jeecg.modules.param.staffUser.mapper.StaffRoleMapper;
import org.jeecg.modules.staff.member.service.StaffService;
import org.jeecg.modules.system.permissions.entity.BikeSysUserApp;
import org.jeecg.modules.system.permissions.mapper.BikeSysUserAppMapper;

import org.jeecg.modules.user.member.dto.MemberPwdReq;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.StringToIntListUtils;
import org.jeecg.modules.work.dispatch.mapper.BikeWorkDispatchMapper;
import org.jeecg.modules.work.repair.mapper.BikeWorkRepairMapper;
import org.jeecg.modules.work.sweep.mapper.BikeWorkSweepMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class StaffServiceImpl implements StaffService {

    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private StaffRoleMapper staffRoleMapper;
    @Resource
    private BikeSysUserAreaMapper bikeSysUserAreaMapper;
    @Resource
    private BikeSysAreaMapper bikeSysAreaMapper;
    @Autowired
    private BikeWorkRepairMapper bikeWorkRepairMapper;
    @Autowired
    private BikeWorkSweepMapper bikeWorkSweepMapper;
    @Autowired
    private BikeWorkDispatchMapper bikeWorkDispatchMapper;
    @Autowired
    private BikeSysUserAppMapper bikeSysUserAppMapper;

    @Override
    public BikeResult login(LoginReq loginReq) {
        String userName= loginReq.getUserName();
        String passWord= loginReq.getPassWord();
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,userName);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);

        if (loginRes == null) {
            return BikeResult.error("0","该用户不存在,请联系管理员",false);
        }

            StringBuilder stringBuilder = new StringBuilder();
        List<String> staffRoleByUserName = staffRoleMapper.getStaffRoleByUserName(loginRes.getUsername());

        if (staffRoleByUserName == null) {
            return BikeResult.error("0","该用户没有分配角色,请联系管理员",false);
        }



        for (int i=0;i<staffRoleByUserName.size();i++) {
            //查询用户菜单权限
            BikeSysUserApp bikeSysUserApp = bikeSysUserAppMapper.selectOne(new QueryWrapper<BikeSysUserApp>().eq("role_id", staffRoleByUserName.get(i)));
            if (bikeSysUserApp!=null){
                if (i==staffRoleByUserName.size()-1){
                    stringBuilder.append(bikeSysUserApp.getRoleMenu());
                }else {
                    stringBuilder.append(bikeSysUserApp.getRoleMenu()).append(",");
                }
            }

        }
        if (StringUtils.isEmpty(stringBuilder.toString())){
            return BikeResult.error("0","该用户没有运维权限,请联系管理员开通",false);
        }
        List<Integer> integers = StringToIntListUtils.StringToIntList(stringBuilder.toString());
        if (integers.size()<1){
            return BikeResult.error("0","该用户没有运维权限,请联系管理员开通",false);
        }


        //情况2：根据用户信息查询，该用户已注销
        //update-begin---author:王帅   Date:20200601  for：if条件永远为falsebug------------
        if (CommonConstant.DEL_FLAG_1.equals(loginRes.getDelFlag())) {
            return BikeResult.error("0","该用户已注销",false);
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(loginRes.getStatus())) {
            return BikeResult.error("0","该用户已冻结",false);
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(userName, passWord, loginRes.getSalt());
        String syspassword = loginRes.getPassword();
        if (!syspassword.equals(userpassword)) {
            return BikeResult.error("0","用户名或密码错误",false);
        }
        // 生成token
        String token = JwtUtil.sign(userName, passWord);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.STAFF_EXPIRE_TIME);
        //保存app ken key
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN+userName,CommonConstant.PREFIX_USER_TOKEN + token);
        JSONObject obj = new JSONObject();

        QueryWrapper<BikeSysUserArea> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userName);
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(wrapper);
        List<LoginRes.AreaList> areaLists = new ArrayList<>();
        if (bikeSysUserArea!=null){
            String ids = bikeSysUserArea.getAreaId();
            String[]  strings= ids.split(",");
            List<String> list = Arrays.asList(strings);
            QueryWrapper qw = new QueryWrapper();
            qw.select("id","name");
            qw.in("id",list);
            qw.eq("has_child","0");
            List<BikeSysArea> list1 = bikeSysAreaMapper.selectList(qw);
            for (BikeSysArea l:list1) {
                LoginRes.AreaList areaList = new LoginRes.AreaList();
                areaList.setId(l.getId());
                areaList.setAreaName(l.getName());
                areaLists.add(areaList);
            }
            obj.put("areaList",areaLists);
        }else {
            obj.put("areaList",areaLists);
        }
        obj.put("id",loginRes.getId());
        obj.put("username",loginRes.getUsername());
        obj.put("realname",loginRes.getRealname());
        obj.put("avatar",loginRes.getAvatar());
        obj.put("sex",loginRes.getSex());
        obj.put("userType",integers);
        obj.put("first",loginRes.getFirst());
        obj.put("token",token);

        return BikeResult.ok("1","登录成功",obj);
    }

    @Override
    public BikeResult getUserInfo(HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);

        //获取用户信息
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,username);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);
        loginRes.setAvatar(loginRes.getAvatar());
        if (!StringUtils.isNotEmpty(username)){
            return BikeResult.error("0","token校验失败",null);
        }

        //自定义对象
        JSONObject jsonObject = new JSONObject();

        StringBuilder stringBuilder = new StringBuilder();
        List<String> staffRoleByUserName = staffRoleMapper.getStaffRoleByUserName(username);
        if (staffRoleByUserName.size()==0){
            return BikeResult.error("0","该用户没有分配角色",null);
        }

        for (int i=0;i<staffRoleByUserName.size();i++) {
            //查询用户菜单权限
            BikeSysUserApp bikeSysUserApp = bikeSysUserAppMapper.selectOne(new QueryWrapper<BikeSysUserApp>().eq("role_id", staffRoleByUserName.get(i)));
                if (bikeSysUserApp==null){
                    continue;
                }
            if (i==staffRoleByUserName.size()-1){
                stringBuilder.append(bikeSysUserApp.getRoleMenu());
            }else {
                stringBuilder.append(bikeSysUserApp.getRoleMenu()).append(",");
            }
        }

        List<Integer> integers = StringToIntListUtils.StringToIntList(stringBuilder.toString());


        jsonObject.put("id",loginRes.getId());
        jsonObject.put("username",loginRes.getUsername());
        jsonObject.put("realname",loginRes.getRealname());
        jsonObject.put("avatar",loginRes.getAvatar());
        jsonObject.put("sex",loginRes.getSex());
        jsonObject.put("phone",loginRes.getPhone());

        //查询用户菜单权限
//        BikeSysUserApp bikeSysUserApp = bikeSysUserAppMapper.selectOne(new QueryWrapper<BikeSysUserApp>().eq("user_id", loginRes.getId()));
        jsonObject.put("userType",integers);
        String[] split = integers.toString().replace("[","").replace("]","").split(",");
        List<String> strings1 = Arrays.asList(split);

        //根据权限查询未完成的单据
        int iconCount=0;
        for (int i=0;i<strings1.size();i++) {
            //dispatch 调度   cleaning保洁 repair维修
             if (strings1.get(i).equals("1")){
                 QueryWrapper qw  = new QueryWrapper();
                 qw.eq("is_dispatch","1");
                 qw.eq("is_solve","0");
                 qw.eq("user_id",loginRes.getId());
                 Integer count = bikeWorkSweepMapper.selectCount(qw);
                 iconCount+=count;
             }else if (strings1.get(i).equals("3")){
                 QueryWrapper qw  = new QueryWrapper();
                 qw.eq("is_dispatch","1");
                 qw.eq("is_solve","0");
                 qw.eq("user_id",loginRes.getId());
                 Integer count = bikeWorkRepairMapper.selectCount(qw);
                 iconCount+=count;
             }else if (strings1.get(i).equals("2")){
                 QueryWrapper qw  = new QueryWrapper();
                 qw.eq("is_dispatch","1");
                 qw.eq("is_solve","0");
                 qw.eq("user_id",loginRes.getId());
                 Integer count = bikeWorkDispatchMapper.selectCount(qw);
                 iconCount+=count;
             }
        }
        jsonObject.put("number",iconCount);

         //查询所负责的区域
        QueryWrapper<BikeSysUserArea> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",loginRes.getUsername());
        BikeSysUserArea bikeSysUserArea = bikeSysUserAreaMapper.selectOne(wrapper);
        List<LoginRes.AreaList> areaLists = new ArrayList<>();
        if (bikeSysUserArea!=null){
            String ids = bikeSysUserArea.getAreaId();
            String[]  strings= ids.split(",");
            List<String> list = Arrays.asList(strings);
            QueryWrapper qw = new QueryWrapper();
            qw.select("id","name");
            qw.in("id",list);
            qw.eq("has_child","0");
            List<BikeSysArea> list1 = bikeSysAreaMapper.selectList(qw);
            if (list1.size()!=0){
                for (BikeSysArea l:list1) {
                    LoginRes.AreaList areaList = new LoginRes.AreaList();
                    areaList.setId(l.getId());
                    areaList.setAreaName(l.getName());
                    areaLists.add(areaList);
                }
            }
            jsonObject.put("areaList",areaLists);
        }else {
            jsonObject.put("areaList",areaLists);
        }


        return BikeResult.ok("1","获取用户信息成功",jsonObject);
    }

    @Override
    public BikeResult updateStaffPassword(MemberPwdReq memberPwdReq, HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(memberPwdReq.getUsername())){
            queryWrapper.eq(LoginRes::getUsername,memberPwdReq.getUsername());
        }else {
            queryWrapper.eq(LoginRes::getUsername,username);
        }
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);

        String passwordEncode = PasswordUtil.encrypt(username, memberPwdReq.getUsedPassWord(), loginRes.getSalt());
        if (!loginRes.getPassword().equals(passwordEncode)){
            return BikeResult.error("0","密码错误！",null);
        }
        String salt = oConvertUtils.randomGen(8);
        String password= PasswordUtil.encrypt(username, memberPwdReq.getNewPassWord(), salt);
        LoginRes loginRes1 = new LoginRes();
        loginRes1.setId(loginRes.getId());
        loginRes1.setPassword(password);
        loginRes1.setSalt(salt);
        int param=staffMapper.updateById(loginRes1);
        if (param==1){
            return BikeResult.ok("1","密码修改成功",null);
        }

         return BikeResult.error("0","密码修改失败",null);
    }

    @Override
    public BikeResult getAgreement() {
        String id = "1008611";
        String a =staffMapper.getAgreementById(id);
        return BikeResult.ok("1","成功",a);
    }
}
